<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #imglist{
            width: 95%;
            margin: 0 auto;
        }

        #imglist img{
            width: 600px;
            height: 350px;
            background: url('../imgs/loading.gif') no-repeat center center;
        }
    </style>
</head>
<body>
    <h1>下划加载图片</h1>

    <div id="imglist">
        <img data-src="../imgs/Meinv001.jpg" >
        <img data-src="../imgs/Meinv002.jpg" >
        <img data-src="../imgs/Meinv003.jpg" >
        <img data-src="../imgs/Meinv004.jpg" >
        <img data-src="../imgs/Meinv005.jpg" >
        <img data-src="../imgs/Meinv006.jpg" >
        <img data-src="../imgs/Meinv007.jpg" >
        <img data-src="../imgs/Meinv008.jpg" >
        <img data-src="../imgs/Meinv009.jpg" >
        <img data-src="../imgs/Meinv010.jpg" >
        <img data-src="../imgs/Meinv011.jpg" >
        <img data-src="../imgs/Meinv012.jpg" >
        <img data-src="../imgs/Meinv013.jpg" >
        <img data-src="../imgs/Meinv014.jpg" >
        <img data-src="../imgs/Meinv015.jpg" >
        
    </div>

    <script>
        
        // 获取img 集合
        
        var imglist = document.getElementById('imglist');
        // console.log(imglist);
        
        var imgs = imglist.getElementsByTagName('img');
        // console.log(imgs);
         
        //获取imglist 的宽度
        var box_width = imglist.offsetWidth;

        //获取视口高度
        var view_height = document.documentElement.clientHeight;

        //计算一排有几个图片 列数
        var x_number = Math.floor(box_width / imgs[0].offsetWidth);

        var first_number = Math.ceil((view_height - imgs[0].offsetTop) / imgs[0].offsetHeight) * x_number;

        var m = 0 ;

        loadImage(m, first_number);

        m += first_number;


        window.onscroll = function(){
            if (m >= imgs.length) return;
            // 获取滚动条 滚动过的距离
            var top = document.body.scrollTop || document.documentElement.scrollTop;

            //获取还未加载的第一章图片到顶部的偏移量
            
            var img_top = imgs[m].offsetTop;

            if ((view_height + top) >= img_top) {
                loadImage(m, x_number);

                m += x_number;
            }
        }


        function loadImage(start, nums) {
            for (var i = start; i <(start + nums); i++){
                if (i >= imgs.length) return;
                (function(i){
                    setTimeout(function(){
                        imgs[i].src = imgs[i].getAttribute('data-src');
                    }, 500);
                })(i);
            }
        }
    </script>
</body>
</html>